package com.zmn.oms.zmn.business.impl.work;

import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.json.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.manager.mq.interfaces.ZmnMQSender;
import com.zmn.oms.business.interfaces.messageV1.app.MessageSendAppService;
import com.zmn.oms.common.annotation.ZsNormalOrderWorkLog;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderPostConsts;
import com.zmn.oms.constant.MessageQueueTopicConstant;
import com.zmn.oms.manager.utils.OmsMqTagConsts;
import com.zmn.oms.model.dto.fcorderpart.expressage.ExpressageDTO;
import com.zmn.oms.model.dto.work.modify.OrderPostListDTO;
import com.zmn.oms.model.entity.post.OrderPost;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.vo.work.modify.OrderPostVO;
import com.zmn.oms.services.interfaces.express.OrderPostService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.work.OrderWorkOrderPostBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName OrderWorkExpressBServiceImpl
 * @Description 快递信息
 * @Author xiaofei
 * @Date 2020/7/24
 * @Version 1.0
 */
@Slf4j
@Service
public class OrderWorkOrderPostBServiceImpl implements OrderWorkOrderPostBService {

    @Autowired
    private OrderPostService orderPostService;
    @Resource
    private ZmnMQSender zmnMQSender;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private MessageSendAppService messageSendAppService;

    @Value("${spring.profiles.active}")
    String activeProfile;

    @Override
    public List<OrderPostVO> listOrderPostByOrderId(Long orderId) {
        List<OrderPost> expresseList = orderPostService.listOrderPostByOrderId(orderId);
        List<OrderPostVO> orderPostList = Lists.newArrayListWithCapacity(expresseList.size());
        expresseList.forEach(orderPost -> {
            OrderPostVO orderPostVO = BeanMapper.map(orderPost, OrderPostVO.class);
            orderPostVO.setItemTypeName(OrderPostConsts.getExpressItemTypeName(orderPost.getItemType()));
            orderPostVO.setStatusName(OrderPostConsts.getPostStatusName(orderPost.getStatus()));
            orderPostList.add(orderPostVO);
        });
        return orderPostList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @ZsNormalOrderWorkLog(type = OrderLogConsts.ORDER_LOG_TYPE_EXPRESS_POST)
    public void saveOrderPostList(OrderPostListDTO orderPostListDTO) {
        List<OrderPost> postList = orderPostListDTO.getPostList();

        orderPostService.deleteOrderPostByOrderId(orderPostListDTO.getOrderId());

        if (CollectionUtil.isNotNullOrEmpty(postList)) {
            orderPostService.insertOrderPostList(orderPostListDTO.getOrderId(), postList);
        }
    }

    @Override
    public void updateOrderPostExpress(ExpressageDTO expressageDTO) {
        // 更新快递信息
        OrderPost orderPost = new OrderPost();
        orderPost.setExpressCode(expressageDTO.getCode());
        orderPost.setExpressCompanyCode(expressageDTO.getCompany());
        orderPost.setValid(GlobalConsts.YES);
        orderPost.setStatus(OrderPostConsts.getZmnPostStatus(expressageDTO.getState()));
        orderPost.setExpressData(JSON.toJSONString(expressageDTO.getList()));

        //如果已签收
        if (Objects.equals(orderPost.getStatus(), OrderPostConsts.ORDERPOST_STATUS_RECEIVED)){
            Long orderId = orderPostService.findOrderIdByExpressCodeAndExpressCompanyCode(orderPost.getExpressCode(),
                    orderPost.getExpressCompanyCode());
            sendMessage(orderId);
        }
        orderPostService.updateOrderPostExpress(orderPost);
    }

    /**
     * 快递签收后，向绩效发送mq消息
     * @param orderId 
     * @return void
     * @author wangxiaokun
     */
    private void sendMessage(Long orderId) {

        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId, orderId);
        if (Objects.isNull(orderWork)){
            return;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderId", orderWork.getOrderId());
        jsonObject.put("workId", orderWork.getWorkId());
        jsonObject.put("plat", orderWork.getPlatWork());
        jsonObject.put("logType", OrderLogConsts.ORDER_LOG_TYPE_EXPRESS_RECEIPT);
        jsonObject.put("operateTime", DateUtil.getNow().getTime());
        jsonObject.put("bizType", orderWork.getBizType());

        // 延迟三秒执行 防止未提交事物 or 同步到es
        long time = System.currentTimeMillis() + 3000;
        String message = com.alibaba.fastjson.JSON.toJSONString(jsonObject);
        String key = String.format("%s-%s", orderId, OrderLogConsts.ORDER_LOG_TYPE_ORDER_SUSPEND);

//        String noticeProfile = "dev,uat,test";
        String noticeProfile = "dev,uat,test,prod,test2";

        if (StringUtils.contains(noticeProfile, activeProfile)) {
            zmnMQSender.sendWithStartDeliverTime(MessageQueueTopicConstant.ZMN_TOPIC_PERF, OmsMqTagConsts.ZMN_TOPIC_PERFORMANCE_ORDER_LOG_NOTICE, key, message, time);
        }
    }

}
